<template>
  <div>
    <div class="head">
      <el-row :gutter="15">
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="getDataPar.keyword" class="input-with-select">
            <el-button slot="append" @click="conditionSearch" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="warning" icon="el-icon-refresh" @click="handleRef">重置</el-button>
        </el-col>
      </el-row>
      <div style="margin-bottom: 10px">
        <el-button icon="el-icon-plus" @click="handleAdd" type="primary">添加</el-button>
        <el-button icon="el-icon-delete" @click="handleBatchDel" type="danger">批量删除</el-button>
      </div>
    </div>
    <div class="table">
      <el-table height="420px" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :data="tableData" :border="true" stripe style="width: 100%" tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="昵称" min-width="140"> </el-table-column>
        <el-table-column prop="role_key" label="角色" min-width="140"> </el-table-column>
        <el-table-column label="操作" width="300" class-name="operate">
          <template slot-scope="scoped">
            <el-button type="primary" icon="el-icon-plus" @click="handleRoleAss(scoped.row.id)">分配权限</el-button>
            <el-button icon="el-icon-edit" @click="handleEdit(scoped.row)">编辑</el-button>
            <el-button icon="el-icon-delete" type="danger" @click="handleDel(scoped.row)">删除</el-button>
          </template>
        </el-table-column> </el-table
      >`
    </div>
    <!-- 添加或修改弹框 -->
    <el-dialog top="20px" :title="dialogTitle + '角色'" :visible.sync="dialogVisible" width="30%" @close="handleClose">
      <add-and-edit ref="bulletBox" @submit="submit" :ruleForm="editObj"></add-and-edit>
    </el-dialog>

    <el-dialog top="20px" title="菜单权限分配" :visible.sync="roleMenuDialogVisible" width="30%">
      <role-assignment :key="roleId" ref="roleMenu" :menuTree="menuTree" :activeMenuTree="activeMenuTree" @roleMenuSubmit="roleMenuSubmit"></role-assignment>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getRoleListPage, addOrEditRole, delRole, batchDelRole, setRoleMenu, getRoleMenu } from '@/api/roleApi.js'
import { getMenuList } from '@/api/menuApi.js'
import addAndEdit from './AddAndEdit.vue'
import RoleAssignment from './RoleAssignment.vue'
import { resRouter } from '../../router'
export default {
  data() {
    return {
      loading: true,
      dialogVisible: false, //添加和修改弹窗控制开关
      roleMenuDialogVisible: false,
      editObj: {}, //修改行对象信息
      dialogTitle: '添加',
      roleId: 0,
      tableData: [],
      selectTableRow: [],
      menuTree: [],
      activeMenuTree: [],
      getDataPar: {
        pageSize: 15,
        currentPage: 1,
        keyword: '',
      },
      total: 0,
    }
  },
  components: {
    addAndEdit,
    RoleAssignment,
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      getRoleListPage(this.getDataPar).then((res) => {
        if (res.data.code != 200) return this.$message.error('数据请求失败')
        this.loading = false
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      })
    },
    //关键字、性别、时间筛选
    conditionSearch() {
      this.getData()
    },
    //重置条件筛选
    handleRef() {
      this.getDataPar = {
        pageSize: 15,
        currentPage: 1,
        keyword: '',
      }
      this.getData()
    },
    handleSelectionChange(val) {
      this.selectTableRow = val
    },
    //添加
    handleAdd() {
      this.dialogTitle = '添加'
      this.dialogVisible = true
      this.editObj = {
        name: '',
        type: '',
      }
    },
    //修改
    handleEdit(val) {
      this.dialogTitle = '修改'
      this.dialogVisible = true
      this.editObj = JSON.parse(JSON.stringify(val))
    },
    //分配权限弹窗开启
    async handleRoleAss(roleId) {
      this.activeMenuTree = []
      this.roleId = roleId
      this.roleMenuDialogVisible = true
      //所有菜单
      let menuTree = await getMenuList()
      this.menuTree = menuTree.data.data

      //选中key，包括父级key
      let checkedKeys = await getRoleMenu({ roleId: roleId })
      this.activeMenuTree = checkedKeys.data.data

      //去除父级key，因为父级选中,子级全部都会选中不管有没有key
      this.menuTree.forEach((item) => {
        if (item.pid == null && item.path == null) {
          let i = this.activeMenuTree.findIndex((m) => m == item.id)
          if (i != -1) {
            this.activeMenuTree.splice(i, 1)
          }
        }
      })
    },
    //权限分配确认按钮
    roleMenuSubmit(menuIds) {
      this.roleMenuDialogVisible = false
      setRoleMenu(`role/setRoleMenu/${this.roleId}`, menuIds).then((res) => {
        if (res.data.code != 200) return this.$message.error(`权限分配失败！！！`)
        this.$message.success(`权限分配成功，请重新登录`)
        // this.$emit("upMenu")
      })
    },
    //删除
    handleDel(row) {
      this.$confirm(`确定删除 ${row.name} 角色吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delRole({ id: row.id }).then((res) => {
            if (res.data.code != 200) return this.$message.error(`删除${row.name}失败！！！`)
            this.$message.success('删除成功!')
            this.getData()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    //批量删除
    handleBatchDel() {
      this.$confirm(`确定此操作吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let idList = []
          let tips = ''
          this.selectTableRow.forEach((item, i) => {
            idList.push(item.id)
            if (i == this.selectTableRow.length - 1) {
              tips += item.name
            } else {
              tips += item.name + ','
            }
          })
          batchDelRole(idList).then((res) => {
            if (res.data.code != 200) return this.$message.error(`批量删除失败！！！`)
            this.$message.success(`${tips} 用户已被删除`)
            this.getData()
          })
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    },
    //提交表单，添加或编辑
    submit(formData) {
      this.dialogVisible = false
      addOrEditRole(formData).then((res) => {
        if (res.data.code != 200) return this.$message.error(`${this.dialogTitle}失败！！！`)
        this.$message.success(`${this.dialogTitle}成功`)
        this.getData()
      })
    },
    //关闭弹框
    handleClose() {
      this.$refs.bulletBox.resetForm()
    },
  },
}
</script>

<style lang="less" scoped>
.block {
  margin-top: 15px;
}
/deep/.operate {
  text-align: right !important;
}
</style>